package com.gzy.mylog.server;

import com.gzy.mylog.controller.paramer.LoginPara;
import com.gzy.mylog.controller.paramer.UserUpdatePara;
import com.gzy.mylog.core.PageList;
import com.gzy.mylog.model.Log;
import com.gzy.mylog.model.User;
import com.gzy.mylog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class UserServer {
    @Autowired
    UserRepository userRepository;
    @Autowired
    AuthServer authServer;


    public User getUserByUsername(String username) {
        User user = userRepository.findUserByUsername(username);
        if (user == null){
            throw new RuntimeException("找不到用户");
        }

        return user;
    }


    public void add(LoginPara para) {
        authServer.signup(para.getUsername(),para.getPassword());
    }

    public void del(Long id) {
        Optional<User> user = userRepository.findById(id);
        if (user.isEmpty()){
            throw new RuntimeException("找不到用户");
        }

        User u = user.get();
        u.setDeleteAt(System.currentTimeMillis());

        userRepository.save(u);
    }

    public void update(Long id, UserUpdatePara para) {
        Optional<User> user = userRepository.findById(id);
        if (user.isEmpty()){
            throw new RuntimeException("找不到用户");
        }
        User u = user.get();
        if (!StringUtils.isEmpty(para.getPassword())){
            u.setPassword(para.getPassword());
        }

        if (!StringUtils.isEmpty(para.getRole())){
            u.setRole(para.getRole());
        }

        if (!StringUtils.isEmpty(para.getAvatar())){
            u.setAvatar(para.getAvatar());
        }
        userRepository.save(u);
    }

    // order = 1  Asc
    // order = 2  Desc
    public PageList<User> page(Integer page, Integer size, Integer order) {
        int offset = (page - 1) * size;

        List<User> pageList;

        if (order == 1) {
            pageList = userRepository.findAllWithPage_Asc(offset, size);
        }else{
            pageList = userRepository.findAllWithPage_Desc(offset, size);
        }


        PageList<User> result = new PageList<>();
        result.setData(pageList);

        result.setCurrPage(page);

        long totalCount =   userRepository.count();

        long totalPage = totalCount / size;

        long mod = totalCount % size;
        if (mod > 0) {
            totalPage++;
        }

        result.setTotalPage(totalPage);

        return result;
    }

    public void enable(Long id) {
        Optional<User> user = userRepository.findById(id);
        if (user.isEmpty()){
            throw new RuntimeException("找不到用户");
        }

        User u = user.get();
        u.setDeleteAt(null);

        userRepository.save(u);
    }
}
